package cn.chainco.cts.security;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

@SuppressWarnings("unused")
public class AuthInterceptor extends AbstractInterceptor{
	private static final long serialVersionUID = 8477797799078151494L;
	private static final String NO_LOGIN = "needLogin"; // 未登陆跳转页面
	private static final String NO_LOGIN_M68 = "needLoginM68"; // 在M68时未登陆跳转页面
	protected static Set<String> notNeedValidateActionSet; // 不需要验证的Action集合
	protected static String[] nameSpaces;
	public static Map<String, Long> needValidateActionMap; // 需要验证Action的集合

	@Override
	public void init(){
		initNotNeedValidateActionSet();
		super.init();
	}

	// 初始化不需要验证的Action集合
	protected void initNotNeedValidateActionSet(){
		if(notNeedValidateActionSet == null){
			notNeedValidateActionSet = new HashSet<String>(64);
		}
		notNeedValidateActionSet.add("index");
		notNeedValidateActionSet.add("login");
		notNeedValidateActionSet.add("logout");
		notNeedValidateActionSet.add("register");

		if(nameSpaces == null){
			nameSpaces = new String[4];
			nameSpaces[0] = "/os/";
			nameSpaces[1] = "/ps/";
			nameSpaces[2] = "/ad/";
			nameSpaces[3] = "/pf/";
		}
	}

	@Override
	public String intercept(ActionInvocation actionInvocation) throws Exception{
		/**
		 * ActionContext actionContext = actionInvocation.getInvocationContext(); String method = actionContext.getName(); Map<?, ?> session =
		 * actionInvocation.getInvocationContext().getSession(); if(CommUtils.isValidStr(method) && isNeedValidateAction(method)){ User user = (User)session.get("s_user"); if(user ==
		 * null){ HttpServletRequest request = (HttpServletRequest)actionContext.get(StrutsStatics.HTTP_REQUEST); String uri = request.getRequestURI(); for(String namespace:
		 * nameSpaces){ if(uri.indexOf(namespace) != -1){ return NO_LOGIN; } } return NO_LOGIN_M68; } }
		 */
		return actionInvocation.invoke();
	}

	protected boolean isNeedValidateAction(String method){
		if(notNeedValidateActionSet == null){
			initNotNeedValidateActionSet();
		}
		return !notNeedValidateActionSet.contains(method);
	}
}